#include "datetime.hpp"
#include <chrono>
#include <ctime>
#include <iomanip>
#include <sstream>
#include <iostream>

DateTime DateTime::now() {
    auto now = std::chrono::system_clock::now();
    time_t now_c = std::chrono::system_clock::to_time_t(now);
    tm local_tm = *std::localtime(&now_c);

    int milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(
        now.time_since_epoch()
    ).count() % 1000;

    return DateTime(
        local_tm.tm_year + 1900,
        local_tm.tm_mon + 1,
        local_tm.tm_mday,
        local_tm.tm_hour,
        local_tm.tm_min,
        local_tm.tm_sec,
        milliseconds
    );
}

std::string DateTime::toString() const {
	std::ostringstream oss;
	oss << std::setfill('0') << std::setw(4) << year << '-'
		<< std::setfill('0') << std::setw(2) << month << '-'
		<< std::setfill('0') << std::setw(2) << day << ' '
		<< std::setfill('0') << std::setw(2) << hour << ':'
		<< std::setfill('0') << std::setw(2) << minute << ':'
		<< std::setfill('0') << std::setw(2) << second << '.'
		<< std::setfill('0') << std::setw(3) << millisecond;
	return oss.str();
}